<template>
    <div class="sys-role p-4 bg-white rounded-lg shadow-sm border border-gray-200">
        <!-- Header -->
        <h2 class="text-lg font-medium pb-2">角色管理</h2>
        <div class="flex flex-wrap justify-between items-center pb-2 gap-2">
            <div class="flex flex-wrap gap-2">
                <!-- 查询表单 -->
                <el-form :model="queryParams" class="mb-4 flex flex-wrap items-end gap-4" inline label-suffix=":">
                    <el-form-item label="搜索" prop="description">
                        <el-input v-model="queryParams.description" placeholder="编码/名称/描述" style="width: 180px" @keydown.enter="search"/>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="queryParams.status" clearable placeholder="全部" style="width: 120px">
                            <el-option :value="1" label="启动"></el-option>
                            <el-option :value="0" label="停用"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button icon="Search" type="primary" @click="search">搜索</el-button>
                        <el-button icon="RefreshRight" @click="reset">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="flex flex-wrap justify-between items-center pb-2 gap-2">
            <!-- 左侧操作 -->
            <div class="flex flex-wrap gap-2">
                <el-button icon="Plus" plain type="primary" @click="handleAdd" v-permission:role:insert>新增</el-button>
                <el-button :disabled="selectedRow.length === 0" icon="Delete" plain type="danger"
                           @click="handleBatchDelete">批量删除
                </el-button>
            </div>
            <!-- 右侧工具 -->
            <div class="flex flex-wrap gap-2">
            </div>
        </div>
        <div class="border border-gray-200 overflow-hidden flex flex-col">
            <div class="p-2 flex justify-center">
                <el-table ref="tableRef" :data="roleList" @selection-change="onSelectionChange">
                    <el-table-column :selectable="row => !['ROLE_ADMIN', 'ROLE_USER'].includes(row.roleCode)"
                                     prop="selectedRow"
                                     type="selection"/>
                    <el-table-column label="名称" prop="roleName" width="120">
                        <template #default="{row}">
                            <el-popover
                                :content="row.remark||'暂无'"
                                placement="right-start"
                                style="text-align: center"
                                trigger="hover"
                            >
                                <template #reference>
                                    <div>{{ row.roleName }}</div>
                                </template>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column label="角色编码" prop="roleCode">
                        <template #default="{row, $index, column}">
                            <el-button type="text" @click="handleDetail(row)" v-permission:role:detail="row">{{ row.roleCode }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" prop="status">
                        <template #default="{row}">
                            <el-tag :type="asyncStatus(row.status).type" disable-transitions>
                                {{ asyncStatus(row.status).text }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="最后更新" prop="updateTime" sortable>
                        <template #default="{row, $index, column}">
                            {{ row.updateTime }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="240">
                        <template #default="{row, $index, column}">
                            <div>
                                <el-button size="small" type="primary" @click="handleUpdate(row)" v-permission:role:update="row">编辑</el-button>
                                <el-button v-if="!['ROLE_ADMIN', 'ROLE_USER'].includes(row.roleCode)" plain size="small" type="danger" @click="handleDelete(row)" v-permission:role:delete="row">删除</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <div class="p-4 flex justify-end">
                <el-pagination
                    :current-page="current"
                    :page-size="size"
                    :page-sizes="[10, 20, 50, 100]"
                    :total="total"
                    layout="total, prev, pager, next, sizes, jumper"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                />
            </div>
        </div>
        <div class="bg-white shadow-sm">
            <el-dialog ref="dialogRef" v-model="dialogVisibleModel.isVisible"
                       :lock-scroll="true" :title="dialogVisibleModel?.title"
                       @close="close">
                <router-view v-if="dialogVisibleModel?.isVisible" v-slot="{Component}">
                    <component :is="Component"
                               :data="dialogVisibleModel?.data"
                               @cancel="()=>{dialogVisibleModel.isVisible= false}"
                               @submit="submit"/>
                </router-view>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import {reactive, ref, onMounted} from "vue";
import {useRouter} from 'vue-router';
import useSysRole from "@/composables/useSysRole.js";
import instance from "@/api/request.js";
// 模态框
const router = useRouter();
const dialogRef = ref();

const dialogVisibleModel = reactive({
    isVisible: false,
    option: null,
    title: '模态框',
    data: null
})

const submit = () => {
    dialogVisibleModel.isVisible = false;
    search();
}

const close = () => {
    dialogVisibleModel.isVisible = false;
    router.push("/role")
    search();
}

const handleAdd = () => {
    const dialogSaveModel = {
        isVisible: true,
        option: router.currentRoute.value.meta.perms,
        title: router.currentRoute.value.meta.title,
        data: null
    }
    Object.assign(dialogVisibleModel, dialogSaveModel);
    router.push("/role/add").then((v) => {

    })
}
const handleUpdate = (row) => {
    router.push(`/role/edit/${row.roleCode}`).then((v) => {
        const dialogSaveModel = {
            isVisible: true,
            option: router.currentRoute.value.meta.perms,
            title: router.currentRoute.value.meta.title,
            data: row
        }
        Object.assign(dialogVisibleModel, dialogSaveModel);
    })
}

const handleDetail = (row) => {
    router.push(`/role/${row.roleCode}`).then((v) => {
        const dialogSaveModel = {
            isVisible: true,
            option: router.currentRoute.value.meta.perms,
            title: router.currentRoute.value.meta.title,
            data: row
        }
        Object.assign(dialogVisibleModel, dialogSaveModel);
    })
}

const handleDelete = (row) => {
    ElMessageBox.confirm(`确认删除${row.roleName}吗？`).then(yes => {
        ElMessage.closeAll()
        instance.post("/role/remove", {
            roleCode: row.roleCode
        }).then(res => {
            console.log(res.data)
            ElMessage.success("删除一个角色")
            search();
        })
    }).catch(no => {
    })
}

const handleBatchDelete = () => {
    ElMessageBox.confirm(`将删除${selectedRow.value.length}条记录，确定吗？`).then(yes => {
        ElMessage.closeAll()
        instance.post("/role/remove_batch", selectedRow.value).then(res => {
            console.log(res.data)
            ElMessage.success(`${selectedRow.value.length}`)
            search();
        })
    }).catch(no => {
    })
}
const tableRef = ref();

function asyncStatus(status) {
    const statusVO = {
        '1': {
            text: '启用',
            type: 'primary',
        },
        '0': {
            text: '停用',
            type: 'danger'
        },
    }
    return statusVO[status];
}

const selectedRow = ref([])
const onSelectionChange = (selection) => {
    selectedRow.value = selection.map(s => s.roleCode);
    console.log(selectedRow.value)
};


const {
    queryParams,
    roleList,
    current,
    size,
    total,
    loading,
    search,
    reset,
    refresh,
    handleCurrentChange,
    handleSizeChange,
} = useSysRole();

onMounted(() => {
    search();
})
</script>

<style lang="scss" scoped>

</style>